/**
 * 侧边栏
 * 不同子路径下的页面会使用不同的侧边栏
 */

const IT_BASE_URL = '/10.知识管理/01.IT'


const IT_URL_MAP = {

    '/01.web': [
        {
            text: "js总结",
            link: "/01.web/js总结.html",
        },
        {
            text: "css总结",
            link: "/01.web/css总结.html",
        },
        {
            text: "vue2与vue3",
            link: "/01.web/vue2与vue3.html",
        },


    ],

    '/02.server': [

        {
            text: "java",
            collapsible: true,     //是否折叠
            children: [
                { text: "stream流处理", link: "/02.server/java/stream.html" },
                { text: "反射", link: "/02.server/java/反射.html" },
                { text: "ASM字节码操作", link: "/02.server/java/ASM字节码操作.html" },
                { text: "正则表达式", link: "/02.server/java/正则表达式.html" },
            ],
        },

        {
            text: "JVM",
            collapsible: true,     //是否折叠
            children: [
                { text: "类加载器系统", link: "/02.server/知识点/jvm.html#类加载器系统" },
                {
                    text: "运行时数据区",
                    children: [
                        { text: "jvm内存模型", link: "/02.server/知识点/jvm.html#jvm内存模型" },
                        { text: "对象创建流程", link: "/02.server/知识点/jvm.html#对象创建流程" },
                        { text: "垃圾收集", link: "/02.server/知识点/jvm.html#垃圾收集" },
                    ],
                },
            ],
        },

        {
            text: "并发",
            collapsible: true,     //是否折叠
            children: [
                { text: "JMM 内存模型", link: "/02.server/并发/JMM.html" },
                { text: "volatile", link: "/02.server/并发/JMM.html#volatile" },
                { text: "synchronized", link: "/02.server/并发/synchronized.html" },
                { text: "线程池", link: "/02.server/并发/线程池.html" },
            ],
        },

        {
            text: "数据库",
            collapsible: true,     //是否折叠
            children: [
                {
                    text: "mysql",
                    children: [
                        { text: "数据结构", link: "/02.server/知识点/mysql.html#数据结构" },
                        { text: "存储引擎", link: "/02.server/知识点/mysql.html#存储引擎" },
                        { text: "事务与MVCC", link: "/02.server/知识点/mysql.html#事务与mvcc" },
                        { text: "BufferPool缓存", link: "/02.server/知识点/mysql.html#innodb-引擎执行sql的-bufferpool缓存机制" },
                        { text: "优化", link: "/02.server/知识点/mysql.html#优化" },
                    ],
                },
                { text: "mysql8.0特性", link: "/02.server/mysql/mysql8.0特性.html" },
                { text: "Sharding-jdbc", link: "/02.server/mysql/sharding-jdbc.html" },
                { text: "Canal", link: "/02.server/mysql/canal.html" },
            ],
        },
        {
            text: "redis",
            collapsible: true,     //是否折叠
            children: [
                { text: "redis", link: "/02.server/redis/redis.html" },
                { text: "RedisTemplate", link: "https://blog.csdn.net/lydms/article/details/105224210?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-105224210-blog-82011670.pc_relevant_3mothn_strategy_and_data_recovery&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-105224210-blog-82011670.pc_relevant_3mothn_strategy_and_data_recovery&utm_relevant_index=2" },
            ],
        },

        {
            text: "mybatis",
            collapsible: true,     //是否折叠
            children: [
                { text: "mybatis语法", link: "/02.server/mybatis/mybatis语法.html" },
                { text: "多数据源", link: "/02.server/mybatis/多数据源.html" },
                { text: "多租户", link: "/02.server/mybatis/多租户.html" },
                { text: "多租户（升级版）", link: "/02.server/mybatis/多租户（升级版）.html" },
                { text: "mp代码生成器", link: "/02.server/mybatis/代码生成.html" }
            ],
        },

        {
            text: "spring boot",
            collapsible: true,     //是否折叠
            children: [
                {
                    text: "AOP",
                    children: [
                        { text: "动态代理", link: "/02.server/springBoot/aop/动态代理.html" },
                        { text: "AOP详情", link: "/02.server/springBoot/aop/AOP.html" },
                    ],
                },
                { text: "自动配置", link: "/02.server/知识点/springBoot.html" },
                { text: "spring-EL表达式", link: "/02.server/springBoot/spring-EL表达式.html" },
                { text: "请求返回统一实体", link: "/02.server/工具包/spring请求返回统一实体/spring请求返回统一实体.html" },
            ],
        },
        {
            text: "spring cloud alibaba",
            collapsible: true,     //是否折叠
            children: [
                { text: "spring cloud alibaba", link: "/02.server/springCloudAlibaba/spring cloud alibaba.html" },
                { text: "Nacos", link: "/02.server/springCloudAlibaba/Nacos.html" },
            ],
        },
        {
            text: "消息队列",
            collapsible: true,     //是否折叠
            children: [
                { text: "消息队列", link: "/02.server/消息队列/消息队列.html" },
                { text: "RabbitMQ", link: "/02.server/消息队列/RabbitMQ.html" },
            ],
        },


    ],

    '/03.operation': [
        {
            text: "快速部署",
            link: "/03.operation/快速部署.html",
        },
        {
            text: "linux命令",
            children: [
                { text: "线上分析", link: "/03.operation/线上分析.html" },
                { text: "常用命令", link: "/03.operation/linux命令.html" }
            ],
        },
        {
            text: "shell脚本",
            collapsible: true,     //是否折叠
            children: [
                { text: "kill端口重启", link: "/03.operation/shell脚本/kill端口重启.html" },
                { text: "监听端口重启jar", link: "/03.operation/shell脚本/监听端口重启jar.html" },
                { text: "文件批量移动重命名", link: "/03.operation/shell脚本/文件批量移动重命名.html" },
            ],
        },
        {
            text: "nginx配置",
            link: "/03.operation/nginx/配置.html",
        },
        {
            text: "git",
            link: "/03.operation/git.html",
        },
        {
            text: "docker",
            collapsible: false,     //是否折叠
            children: [
                { text: "Docker命令", link: "/03.operation/docker.html#docker" },
                { text: "Docker镜像制作", link: "/03.operation/docker.html#镜像制作" },
                { text: "Harbor仓库", link: "/03.operation/docker_Harbor仓库.html" },
            ],
        },

        {
            text: "jenkins自动化",
            collapsible: false,     //是否折叠
            children: [
                { text: "Jenkins", link: "/03.operation/jenkins.html" },
                { text: "k8s", link: "/03.operation/K8s.html" },
                { text: "jenkinx pipeline + jar/k8s", link: "/03.operation/jenkinx_pipeline.html" },
            ],
        },

    ]

}



export default urlMap();


function urlMap() {

    var totalUrlObj = {}

    // IT 类
    handleUrlMap(totalUrlObj, IT_BASE_URL, IT_URL_MAP)

    // 自动生成
    var autoSideBar = createAutoSideBar()
    // console.log(JSON.stringify(autoSideBar))
    handleUrlMap(totalUrlObj, '', autoSideBar)
    return totalUrlObj;
}

/*********************  处理中文路径匹配-开始 ***********************************/


function handleUrlMap(totalUrlObj, baseUrl, oldUrlObj) {
    for (let key in oldUrlObj) {
        var urlList = oldUrlObj[key]
        handlerUrlList(baseUrl, urlList)
        totalUrlObj[handleUrl(baseUrl, key)] = urlList
    }
}

function handlerUrlList(baseUrl, urlList) {
    urlList.forEach(item =>{
        if (item.link) {
            item.link = handleUrl(baseUrl, item.link)
        }
        if (item.children) {
            handlerUrlList(baseUrl, item.children)
        }
    })
}

function handleUrl(baseUrl, url){
    if (/(http|https):\/\/\S*/.test(url)){
        return url
    }
    return encodeURI(baseUrl + url)
}

/*********************  处理中文路径匹配-结束 ***********************************/


/*********************  自动生成侧边栏-开始 ***********************************/

import shelljs from "shelljs"
import fs from "fs"
import path from "path"
import {getMatchingAutoList} from "./pagePatternsHandler";


function readDirToObjTreeTool(){

    let foldPath = shelljs.pwd().stdout // 当前目录的绝对路径
    let objTree = []

    function recursion(foldPath, data) {


        let files = fs.readdirSync(foldPath)
        // 1.目录循环
        files.forEach(item => {
            //是否是目录
            let isDir = fs.statSync(`${foldPath}/${item}`).isDirectory()

            if (isDir) {
                data.push({
                    name: item,
                    children: [],
                    path: `${foldPath}/${item}`,
                    isDir
                })
            } else if (!isDir && item !== '.DS_Store') {
                data.push({
                    name: item,
                    isDir
                });
            }

        })
        data.forEach(item => {
            if (item.isDir) {
                recursion(item.path, item.children)
            }
        })
    }


    const docs = 'xiaopengBrain'
    recursion(path.join(foldPath, docs), objTree)
    return objTree
}



//创建侧边导航栏
function createAutoSideBar(){
    const dirData = readDirToObjTreeTool();
    const sidebar = {};
    var autoList = getMatchingAutoList()

    // 筛选判断逻辑
    const isTarget = (path) : boolean => {
        for (let i in autoList){
            let targetPath = autoList[i]
            if (path.indexOf(targetPath) != -1) {
                return true;
            }
        }
        return false;
    }

    // 自动去除文件名字的 `数字.` 部分
    const handleText = (text) => {
        return  text.replace(new RegExp('\\d*\\.'), '')
    }

    let firstLeaveList = []
    // 参数： path:上层路径  _dirData:文件树形数据  pathLeave:目录等级（第几层开始 匹配 上， 1作为第一层目录）
    const recursion = (path, _dirData, pathLeave:number=0) => {
        const _data = [];
        _dirData.forEach(data => {
            const _path = `${path}/${data.name}`;

            if (data.isDir) {
                var currentPathLeave = isTarget(_path) ? pathLeave + 1 : pathLeave
                let children = recursion(_path, data.children, currentPathLeave)
                // 子层没有 父层就不需要
                if (children && children.length > 0) {
                    let node = {
                        text: handleText(data.name),
                        collapsable: true,
                        children: children,
                        path: _path,   // 内部判断用， vuepress 目录不需要
                    }
                    _data.push(node)
                    if (currentPathLeave == 1){
                        firstLeaveList.push(node)
                    }
                }
                return;
            }

            const names = data.name.split(".");
            //不是MD文件不生成对应侧边栏
            if(names[names.length-1].toUpperCase() !== "MD"){
                return;
            }

            if (isTarget(_path)){
                _data.push({
                    text: handleText(data.name.slice(0, data.name.lastIndexOf("."))),
                    link: _path
                })
            }
        })
        return _data;
    }

    // 第一层 转对象
    // let list = recursion('', dirData)
    recursion('', dirData)
    let list = firstLeaveList
    list.forEach(item => {
        const path = item.path;
        if (path){
            if (!item.children[0].children) {
                // 如果目录结构只有单层，下一层就是md 没有目录
                sidebar[`${path}/`] = [{
                    text: item.text,
                    collapsable: item.collapsable,
                    children: item.children,
                }]
            } else {
                // 如果目录是多层， 省略上面的顶层好看点
                sidebar[`${path}/`] = item.children
            }
        }
    });
    return sidebar;
}


/*********************  自动生成侧边栏-结束 ***********************************/
